<template>
    <div>
          <page-header @toLastPage="toLastPage">
            <template v-slot:title>
                <div>
                    选择联系人
                </div>
            </template>
        </page-header>
         <div class="header-search">
    <van-field
        v-model="search"
        left-icon="search"
        placeholder="搜索"
    />
        </div>
        <div class="content">
        <van-index-bar>
    <van-checkbox-group v-model="result" checked-color='#07C160'>
  <div v-for="(item,index) in newFriendsList" :key="index">
    <div>
      <van-index-anchor :index="item.index" />
<div v-for="(item1,index1) in item.information" :key="index1">
    <van-cell value="">
  <!-- 使用 title 插槽来自定义标题 -->
    <template #title >
        <van-checkbox :name='item1.F_FriendID'>
             <van-image
            width="1.5rem"
            height="1.5rem"
            radius=".2rem"
            lazy-load
            fit="cover"
            class="f-center"
            :src="item1.avatar"
            />
            <span class="name">{{item1.name}}</span>
        </van-checkbox>
    </template>
  </van-cell>
</div>
    </div>
  </div>
  </van-checkbox-group>
        </van-index-bar>
        </div>
    <div class="bottom van-hairline--bottom">
            <div class="right"><van-button type="primary" size="small" :disabled='disabled' @click="addToGroup">
                <span>完成</span>
                <span v-if="result.length!==0">({{result.length}})</span>
                </van-button></div>
        </div>
    </div>
</template>
<script>
import pageHeader from '../common/pageHeader';
import {Meteor} from 'meteor/meteor';
import { friends,groupUser,image, messages,user } from '../../../api/collections/index';
var pinyin = require("pinyin");
export default {
    components:{
        pageHeader
    },
    methods:{
        toLastPage(){
            this.$router.go(-1)
        },
       addToGroup(){
        this.result.forEach(e=>{
        //    创建群成员
        const getUser = user.findOne({_id:e})
            Meteor.call('groupUser.create',{
                gid:this.groupId,
                userId:e,
                add_time:new Date().getTime(),
                groupName:getUser.nickname,
                groupRemark:'',
                showGroupItemNIck:true
            })
        //    插入进群消息
            Meteor.call('message.create',{
                M_IsGroup:true,
                M_PostMessages:{inviteId:this.id,inviteeId:e},
                M_Status:false,//消息状态(0:已读，1:未读)
                M_Time:new Date().getTime(),//消息发送时间
                M_MessagesType:'invite',//消息类型
                M_FromUserID:this.id,//发送者Id
                M_ToUserID:e,//接收者Id
                M_GroupId:this.groupId
            },(err,res)=>{
                if(err){
                    this.$toast(err)
                }
                else{
                    if(e==this.result[this.result.length-1]){
                        this.lastMsg = res
                    }
                }
            })
        })
       },
               // 创建首页消息表
        createIndexMsg(id,data,arr){
        var msg = {
        I_UserId:id,
        I_OtherId:this.groupId,
        I_Type:'group',
        I_LastMsgId:data,
        I_isTop:false
      }
      let num = 0
      if(arr){
        arr.forEach((e) => {
        if(e.M_ToUserID==id&&e.M_Status == false&&e.M_MessagesType!=='invite'){
          num = num+1
        }
      })
      }
      msg.I_noReadCount = num
      Meteor.call('indexMsg.create',msg) 
    }
    },
    computed:{
        disabled(){
            if(this.result.length>0)return false
            else return true
        }
    },
    data() {
        return {
            id:sessionStorage.getItem('user'),
            groupId:this.$route.params.id,
             // 索引栏
            indexList:['*', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
            newFriendsList:[],
            result:[],
            lastMsg:''
        }
    },
    meteor: {
    $subscribe: {
      'userInf': []
    },
    friendsList(){
       let listArr = friends.find({F_UserID:this.id}).fetch()
       let inUser = groupUser.find({gid:this.groupId}).fetch()
       if(listArr.length == 0){
           return this.showLoading = false
       }
        else{
        let newArr = []
       let index = 0
         listArr.forEach(e => {
             if(inUser.every(item=>{return item.userId !== e.F_FriendID})){
            Meteor.call('image.find',e.F_FriendAvatarId,(err,res)=>{
             if(err){
               this.$toast(err.error)
             }
             else{
               e.avatar = res.base64
            const userInf = user.findOne({_id:e.F_FriendID})
            let check = e.F_beizhu?e.F_beizhu:userInf.nickname
            e.name = check
         let fristName = pinyin(check, { style: pinyin.STYLE_NORMAL, heteronym: true })[0][0].substring(0, 1).toUpperCase();
          //进行判断，给原始json数据添加新的键值对
          if (this.indexList.includes(fristName) == true) { 
           if(newArr.some((item,i) =>{if(item.index == fristName){index=i;return true}})){
             newArr[index].information.push(e)
           }
           else{
             let arr = []
             arr.push(e)
             newArr.push({index:fristName,information:arr})
           }
          } else {
           if(newArr.some((item,i) =>{if(item.index == '#'){index=i;return true}})){
             newArr[index].information.push(e)
           }
           else{
             let arr = []
             arr.push(e)
             newArr.push({index:'#',information:arr})
           }
          }
             }
           })  
             }  
        });
       return newArr
        }
    },
    groupMsgList(){
    return messages.find({M_GroupId:this.groupId}).fetch()
    },
    groupUserList(){
        return groupUser.find({gid:this.groupId}).fetch()
    }
       },
       watch:{
      friendsList(){
        if(this.friendsList.length>0){
          this.newFriendsList=[...this.friendsList]
          this.newFriendsList.sort((item1,item2)=>{
            let val1 = item1.index
            let val2 = item2.index
            if (val1 < val2) {
              return -1;
          } else if (val1 > val2) {
              return 1;
          } else {
              return 0;
          }   
          })
           this.showLoading = false
        }
        else{
            setTimeout(()=>{
                 this.showLoading = false
            },500)
        }
      },
       //   创建群聊成功时获取群消息,设置首页消息框信息
      lastMsg(){
          if(this.lastMsg!==''){
            let arr = this.groupUserList
              let list = this.groupMsgList
            arr.forEach((e)=>{
              this.createIndexMsg(e.userId,this.lastMsg,list)
            }) 
            this.$router.push('/home')
          }
      }
       }
}
</script>
<style scoped>
  .header-search{
        position: fixed;
        top: 1.5rem;
        left: 0;
        right: 0;
        z-index: 999;
        box-shadow: 0 .05rem .05rem -.05rem #888;
    }
   .header-search .van-cell{
       padding:.3rem;
   }
   .content{
        margin-top: 3.1rem;
        margin-bottom: 3.2rem;
    }
      .bottom{
        padding:.5rem;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #f3f3f3;
    }
    .right{
        text-align: right;
    }
    .right .van-button--small{
        height: 1.2rem;
    }
    .name{
  display: inline-block;
  position: relative;
  top: -.5rem;
  font-size: .6rem;
  left: .4rem;
}
</style>